package cat.music.ut.ui.dialog

import android.os.Environment
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import cat.music.ut.adapter.QualityMusicAdapter
import cat.music.ut.base.BaseBottomFragment
import cat.music.ut.bean.AudioInfo
import cat.music.ut.bean.SearchResult
import cat.music.ut.comm.http.FileNameSanitizer
import cat.music.ut.databinding.DialogDownloadBinding
import cat.music.ut.viewmodel.DownloadViewModel
import cat.music.ut.viewmodel.SearchViewModel
import com.arialyy.aria.core.Aria
import kotlinx.coroutines.launch
import java.io.File

class DownloadDialogFragment private constructor():BaseBottomFragment<DialogDownloadBinding>() ,QualityMusicAdapter.Listener{
    private lateinit var data:SearchResult
    private val mQualityMusicAdapter by lazy { QualityMusicAdapter(requireActivity(),data.audioInfos) }
    private val mDownloadViewModel by lazy { ViewModelProvider(this)[DownloadViewModel::class.java] }
    companion object{
        fun create(data:SearchResult): DownloadDialogFragment {
            return DownloadDialogFragment().apply {
                this.data = data
            }
        }
    }
    override fun getViewBinding(): DialogDownloadBinding {
        return DialogDownloadBinding.inflate(layoutInflater)
    }

    override fun initView() {
        mQualityMusicAdapter.listener = this
        vb.rvQ.adapter = mQualityMusicAdapter
        vb.rvQ.layoutManager = LinearLayoutManager(requireActivity())
    }

    override fun clickItem(data: AudioInfo) {
        data.url = ""
        mDownloadViewModel.download(data,this.data)
    }
    override fun observe(){
        mDownloadViewModel.mldDownloadUrl.observe(viewLifecycleOwner){
            if (it != null && it.url.isNotEmpty()) {
                toast("开始下载~")
                val filePath =
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                        .getPath()+"/catMusic/" + String.format(
                        "/%s.%s",
                        FileNameSanitizer.sanitize(data.fileName()),
                        it.format
                    )
                Log.e("TAG", "observe: $filePath" )
                val availableFilePath = FileNameSanitizer.getAvailableFilePath(filePath)
                Log.e("TAG", "availableFilePath: $availableFilePath" )

                File(availableFilePath).parentFile?.apply {
                    if(!exists()){
                        mkdirs()
                    }
                }
                Aria.download(this)
                    .load(it.url)
                    .ignoreCheckPermissions()
                    .setFilePath(
                        availableFilePath
                    )
                    .create()
                lifecycleScope.launch {
                    dismiss()
                }
            }else{
                toast("URL 获取失败！请换别的音质试一下")
            }
        }
    }
}